﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
using Newtonsoft.Json.Linq;
using System.Text;
using NetCoreCMS.Quartz;
using NetCoreCMS.DTO;

namespace NetCoreCMS.Web.Areas.Admin.Controllers.Plugin
{
    public class TaskInfo_ListController : ManageController
    {
        private const string WEB_VIEW = "~/Areas/Admin/Views/Plugin/TaskInfo_List.cshtml";
        private string keywords;
        private int page;
        private int pageSize;
        private int totalCount;
        public ITask_infoService _service { get; set; }
        public ScheduleCenter _scheduleCenter { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (filterContext.Result != null)
                return;
            ChkAdminLevel("taskinfo_list", CMSEnums.ActionEnum.Show.ToString());
            this.keywords = Request.Query["keywords"];
            int.TryParse(Request.Query["pagesize"], out this.pageSize);
            int.TryParse(Request.Query["page"], out this.page);
            if (this.pageSize > 0)
            {
                if (this.pageSize != GetPageSize(10))
                {
                    Response.Cookies.Append("taskinfo_page_size", this.pageSize.ToString());
                }
            }
            else
            {
                this.pageSize = GetPageSize(10);
            }
            ViewBag.Keywords = this.keywords;
            ViewBag.PageSize = this.pageSize;
        }

        //
        // GET: /admin/TaskInfo_List/

        public ActionResult Index()
        {
            RptBind("where id>0" + this.CombSqlTxt(keywords), "sort_id asc, add_time desc");
            return View(WEB_VIEW);
        }

        //设置状态
        [HttpPost]
        public async Task<string> SetStatus()
        {
            int id = int.Parse(Request.Form["id"]);
            int[] Ids = { id};
            string commandName = Request.Form["cmdName"];
            BooleanResult result = new BooleanResult();
            switch (commandName)
            {
                case "Stop":
                    {
                        
                        var list = await _service.GetListByIdsAsync(Ids);
                        if (list?.Count > 0)
                        {
                            list.ForEach(async x =>
                            {
                                await _scheduleCenter.StopJobAsync(x.name, x.group);
                            });
                            result = await _service.UpdateStatusByIdsAsync(Ids, (int)TaskInfoStatus.Stopped);
                        }
                    }
                    break;
                case "Start":
                    {
                        var list = await _service.GetListByIdsAsync(Ids);
                        if (list?.Count > 0)
                        {
                            list.ForEach(async x =>
                            {
                                await _scheduleCenter.AddJobAsync(x.name, x.group, x.className, x.assembly, x.cron);
                            });
                            result = await _service.UpdateStatusByIdsAsync(Ids, (int)TaskInfoStatus.Running);
                        }
                    }
                    break;
                case "Delete":
                    {
                        var item = await _service.GetByIdAsync(id);
                        if (item == null)
                        {
                            result.Data = false;
                        }
                        else
                        {
                            await _scheduleCenter.DeleteJobAsync(item.name, item.group);
                            result = await _service.DeleteAsync(id);
                        }
                    }
                    break;
            }
            return "1";// JsonHelper.ObjectToJSON(result);
        }

        //保存排序
        [HttpPost]
        public ActionResult SubmitSave()
        {
            ChkAdminLevel("taskinfo_list", CMSEnums.ActionEnum.Edit.ToString()); //检查权限
            JObject jobject = JObject.Parse(Request.Form["json"]);
            JToken list = jobject["list"];
            foreach (JToken item in list)
            {
                int id = int.Parse(item["id"].ToString());
                int sortId = int.Parse(item["sortId"].ToString());
                _service.UpdateField(id, "sort_id=" + sortId.ToString());
            }
            AddAdminLog(CMSEnums.ActionEnum.Edit.ToString(), "保存任务成功"); //记录日志
            string script = JscriptMsg("保存排序成功！", Utils.CombUrlTxt("index", "keywords={0}", this.keywords));
            return Content(script);
        }

        //批量删除
        [HttpPost]
        public ActionResult SubmitDelete()
        {
            ChkAdminLevel("taskinfo_list", CMSEnums.ActionEnum.Delete.ToString()); //检查权限
            int sucCount = 0; //成功数量
            int errorCount = 0; //失败数量
            JObject jobject = JObject.Parse(Request.Form["json"]);
            JToken list = jobject["list"];
            foreach (JToken item in list)
            {
                int id = int.Parse(item["id"].ToString());
                if (false)//_service.Delete(id) 禁用删除请用，任务删除
                {
                    sucCount++;
                }
                else
                {
                    errorCount++;
                }
            }
            AddAdminLog(CMSEnums.ActionEnum.Edit.ToString(), "删除任务成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            string script = JscriptMsg("删除成功" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("index", "keywords={0}", this.keywords));
            return Content(script);
        }

        //批量审核
        [HttpPost]
        public ActionResult SubmitAudit()
        {
            ChkAdminLevel("taskinfo_list", CMSEnums.ActionEnum.Audit.ToString()); //检查权限
            JObject jobject = JObject.Parse(Request.Form["json"]);
            JToken list = jobject["list"];
            foreach (JToken item in list)
            {
                int id = int.Parse(item["id"].ToString());
                _service.UpdateField(id, "status=0");
            }

            AddAdminLog(CMSEnums.ActionEnum.Audit.ToString(), "审核任务"); //记录日志
            string script = JscriptMsg("批量审核成功！", Utils.CombUrlTxt("index", "keywords={0}", this.keywords));
            return Content(script);
        }

        private void RptBind(string _strWhere, string _orderby)
        {
            int.TryParse(Request.Query["page"], out this.page);
            this.page = this.page <= 0 ? 1 : this.page;
            ViewData["list"] = _service.GetList(this.page, this.pageSize, _strWhere, _orderby, null);
            this.totalCount = _service.RecordCount(_strWhere);
            string pageUrl = Utils.CombUrlTxt("index", "keywords={0}&page={1}", this.keywords, "__id__");
            ViewBag.PageContent = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);

            ViewBag.Keywords = this.keywords;
            ViewBag.PageNum = this.pageSize.ToString();
            ViewBag.Page = this.page.ToString();
        }

        private int GetPageSize(int _default_size)
        {
            int _pageSize;
            if (!int.TryParse(Request.Cookies["taskinfo_page_size"], out _pageSize))
            {
                if (_pageSize > 0)
                {
                    return _pageSize;
                }
            }
            return _default_size;
        }

        private string CombSqlTxt(string _keywords)
        {
            StringBuilder builder = new StringBuilder();
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                builder.Append(" and name link '%" + _keywords + "%'");
            }
            return builder.ToString();
        }
    }
}